package com.hzf.wxplatform.web.controller.manager.owner;

import com.alibaba.fastjson.JSONArray;
import com.hzf.api.rpc.api.ApiService;
import com.hzf.common.base.BaseController;
import com.hzf.common.util.ByteUtils;
import com.hzf.common.util.RedisUtil;
import com.hzf.config.dao.model.ConfigRegion;

import com.hzf.ucenter.dao.model.UcenterUser;
import com.hzf.ucenter.dao.model.UcenterUserCity;
import com.hzf.ucenter.dao.model.UcenterUserExample;
import com.hzf.workman.dao.model.WorkmanManinfo;
import com.hzf.workman.dao.model.WorkmanManinfoCase;
import com.hzf.workman.dao.model.WorkmanManinfoCaseExample;
import com.hzf.wxplatform.common.WxplatformResult;
import com.hzf.wxplatform.common.WxplatformResultConstant;
import com.hzf.wxplatform.common.utils.UcenterUserUtils;
import com.hzf.wxplatform.web.utils.GeoHashHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/ownerWorkman")
public class OwnerWorkmanController extends BaseController {
    @Autowired
    ApiService apiService;

    @RequestMapping(value="/lockSheji")
    public String  lockSheji(Model model, HttpServletRequest request ){
        HttpSession session = request.getSession();
        UcenterUser ucenterUser = new UcenterUser();
        ConfigRegion configRegion = new ConfigRegion();
        byte[] user = UcenterUserUtils.getUser(session);
        if (null == user) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        ucenterUser = (UcenterUser) ByteUtils.ByteToObject(user);

        if (null == ucenterUser) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        return  thymeleaf("/SJS/SJS_LookSheJiShi");

    }
    @RequestMapping(value = "/lockDesigner",method = RequestMethod.POST)
    @ResponseBody
    public Object lockDesigner(int distanceType,HttpServletRequest request,Model model){



        /*   GeoHash geoHash = GeoHash.fromCoordinate(lat,lng);*/
        HttpSession session = request.getSession();
        UcenterUser ucenterUser = new UcenterUser();
        ConfigRegion configRegion = new ConfigRegion();
        byte[] user = UcenterUserUtils.getUser(session);
        ucenterUser = (UcenterUser) ByteUtils.ByteToObject(user);

        String dqaddress = RedisUtil.get("dangqianweizhi"+ucenterUser.getId());
        net.sf.json.JSONObject jsonobject = net.sf.json.JSONObject.fromObject(dqaddress);
        UcenterUserCity usercity= (UcenterUserCity) net.sf.json.JSONObject.toBean(jsonobject,UcenterUserCity.class);
        double lat=usercity.getLat();
        double lng=usercity.getLng();
        DecimalFormat df = new DecimalFormat("######0.00");

        if (null == ucenterUser) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        byte[] address = UcenterUserUtils.getAddress(ucenterUser.getId());
        configRegion = (ConfigRegion) ByteUtils.ByteToObject(address);

        int distanceCount = 0;
// N, NE, E, SE, S, SW, W, NW
        if (distanceType == 0) {
            distanceCount = 2000;
        } else if (distanceType == 1) {
            distanceCount = 5000;

        } else if (distanceType == 2) {
            distanceCount = 10000;

        } else if (distanceType == 3) {
            distanceCount = 20000;

        } else if (distanceType == 4) {
            distanceCount = 50000;

        }
        String json = RedisUtil.get(ucenterUser.getId() + "WorkMan");
        List<WorkmanManinfo> listarray = JSONArray.parseArray(json, WorkmanManinfo.class);
        if(null!=listarray&&0!=listarray.size()){}else{
            listarray=new ArrayList<>();
        }
        List<WorkmanManinfo> list=new ArrayList<>();
        list = selcetDneedDesigner(distanceCount, lat, lng, ucenterUser, configRegion);

        for (WorkmanManinfo dneedsDesigner : list) {

            com.github.wenhao.geohash.GeoHash geoHash = com.github.wenhao.geohash.GeoHash.fromLong(dneedsDesigner.getGeoCode());
            double distance = geoHash.distance(lat, lng);
            double distanceKm = distance / 1000;
            dneedsDesigner.setDistanceKm(Double.valueOf(df.format(distanceKm)));
            UcenterUserExample ucenterUserExample  = new UcenterUserExample();
            ucenterUserExample.createCriteria().andIdEqualTo(dneedsDesigner.getUserId());
            ucenterUser = apiService.getUser(ucenterUserExample);
            dneedsDesigner.setUserName(ucenterUser.getUserName());
            WorkmanManinfoCaseExample dneedsDesignerCaseExample = new WorkmanManinfoCaseExample();
            dneedsDesignerCaseExample.createCriteria().andUserIdEqualTo(ucenterUser.getId());
            List<WorkmanManinfoCase> caseList  =apiService.selectWorkmanManinfoCase(dneedsDesignerCaseExample);
            dneedsDesigner.setAnliCount(caseList.size());
            dneedsDesigner.setPhone(ucenterUser.getPhone());
        }


        String json1 = JSONArray.toJSONString(list);
        RedisUtil.del_add(ucenterUser.getId() + "WorkMan", json1);
        Map map = new HashMap();
        map.put("lng", lng);
        map.put("lat", lat);
        map.put("distanceType", distanceType);
        map.put("list", list);
        return new WxplatformResult(WxplatformResultConstant.SUCCESS, map);

    }
    private List<WorkmanManinfo> selcetDneedDesigner(int dict, double lat, double lng, UcenterUser ucenterUser,  ConfigRegion configRegion) {
        Map<String,Long>map= GeoHashHelper.getMax(lat,lng,dict);
        List<WorkmanManinfo> list = apiService.selectByPrimaryWorkmanManinfo(configRegion.getRegionNumber().intValue(),0,map.get("min0"), map.get("max0"),
                map.get("min1"), map.get("max1"),
                map.get("min2"), map.get("max2"),
                map.get("min3"), map.get("max3"),
                map.get("min4"), map.get("max4"),
                map.get("min5"), map.get("max5"),
                map.get("min6"), map.get("max6"),
                map.get("min7"), map.get("max7"),
                map.get("min8"), map.get("max8"));
        int a = 1000;

        if(null==list||list.size()<4){
            for(int i =1000;i<50000;i++){
                if(dict==50000){
                    map= GeoHashHelper.getMax(lat,lng,dict);
                    list =  apiService.selectByPrimaryWorkmanManinfo(configRegion.getRegionNumber().intValue(),0,map.get("min0"), map.get("max0"),
                            map.get("min1"), map.get("max1"),
                            map.get("min2"), map.get("max2"),
                            map.get("min3"), map.get("max3"),
                            map.get("min4"), map.get("max4"),
                            map.get("min5"), map.get("max5"),
                            map.get("min6"), map.get("max6"),
                            map.get("min7"), map.get("max7"),
                            map.get("min8"), map.get("max8"));
                    List<WorkmanManinfo> removeList = new ArrayList<>();

                    if(null!=list) {
                        for (WorkmanManinfo dneedsDesigner : list) {

                            com.github.wenhao.geohash.GeoHash geoHash = com.github.wenhao.geohash.GeoHash.fromLong(dneedsDesigner.getGeoCode());
                            double distance = geoHash.distance(lat, lng);
                            if (distance > dict) {
                                removeList.add(dneedsDesigner);
                            } else {
                            }
                        }
                        list.removeAll(removeList);
                    }

                    if(null!=list&&list.size()>=4){
                        break;
                    }else{
                        break;

                    }
                }else{
                    map= GeoHashHelper.getMax(lat,lng,dict);
                    list =  apiService.selectByPrimaryWorkmanManinfo(configRegion.getRegionNumber().intValue(),0,map.get("min0"), map.get("max0"),
                            map.get("min1"), map.get("max1"),
                            map.get("min2"), map.get("max2"),
                            map.get("min3"), map.get("max3"),
                            map.get("min4"), map.get("max4"),
                            map.get("min5"), map.get("max5"),
                            map.get("min6"), map.get("max6"),
                            map.get("min7"), map.get("max7"),
                            map.get("min8"), map.get("max8"));
                    List<WorkmanManinfo> removeList = new ArrayList<>();

                    if(null!=list) {
                        for (WorkmanManinfo dneedsDesigner : list) {

                            com.github.wenhao.geohash.GeoHash geoHash = com.github.wenhao.geohash.GeoHash.fromLong(dneedsDesigner.getGeoCode());
                            double distance = geoHash.distance(lat, lng);
                            if (distance > dict) {
                                removeList.add(dneedsDesigner);
                            } else {
                            }
                        }
                        list.removeAll(removeList);
                    }
                    if(null!=list&&list.size()>=4){
                        break;
                    }else{
                        if(dict==2000){
                            dict=5000;
                        }else if(dict==5000){
                            dict=10000;
                        }else if(dict==10000){
                            dict=20000;
                        }else if(dict==20000){
                            dict=50000;
                        }
                    }
                }

            }
            return list;

        }else{
            return list;

        }




    }
}
